import os
import time
import pathlib
import requests


def create_file(tgt_path):
    path_ins = pathlib.Path(tgt_path)
    if not path_ins.parent.exists():
        path_ins.parent.mkdir(parents=True, exist_ok=True)
    if not path_ins.exists():
        path_ins.touch()
    return tgt_path


def retry_request(retry_count=3, status_code=None, wait_time=1):
    def wrapper(func):
        def inner(*args, **kwargs):
            reason = None
            for _ in range(retry_count):
                try:
                    _result = func(*args, **kwargs)
                    if status_code:
                        if status_code == _result.status_code:
                            return _result
                        else:
                            raise ValueError(f'返回的响应的状态码，不是指定的状态码: {status_code}')
                    return _result
                except Exception as e:
                    reason = e
                    time.sleep(wait_time)
            else:
                raise reason

        return inner

    return wrapper


@retry_request(wait_time=30)
def request_get(*args, **kwargs):
    return requests.get(*args, **kwargs, timeout=30)


def get_path_ins(file_path):
    return pathlib.Path(os.path.abspath(file_path))
